package edu.rpi.tw.escience.stargazer.rest;

import edu.rpi.tw.escience.stargazer.server.StarGazerContext;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.restlet.data.MediaType;
import org.restlet.resource.OutputRepresentation;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;


/**
 * Author: josh
 * Date: Apr 27, 2009
 * Time: 10:51:07 PM
 */
public abstract class CelestialObjectRepresentation extends OutputRepresentation {
    protected final URI resourceURI;
    protected final StarGazerContext context;

    public CelestialObjectRepresentation(final URI resourceURI,
                                         final StarGazerContext context,
                                         final MediaType mediaType) {
        super(mediaType);
        this.resourceURI = resourceURI;
        this.context = context;
    }

    /*public CelestialObjectRepresentation(final MediaType mediaType, long l) {
        super(mediaType, l);
    }*/

    protected Collection<Statement> getStatementsAbout() throws RepositoryException {
        Collection<Statement> statements = new LinkedList<Statement>();

        RepositoryConnection rc = context.getRepository().getConnection();
        try {
            RepositoryResult<Statement> result = rc.getStatements(resourceURI, null, null, false);
            try {
                while (result.hasNext()) {
                    statements.add(result.next());
                }
            } finally {
                result.close();
            }
        } finally {
            rc.close();
        }

        return statements;
    }

    protected Map<URI, Set<Value>> getPropertyValues() throws RepositoryException {
        Map<URI, Set<Value>> map = new HashMap<URI, Set<Value>>();

        for (Statement st : getStatementsAbout()) {
            URI p = st.getPredicate();
            Set<Value> values = map.get(p);
            if (null == values) {
                values = new HashSet<Value>();
                map.put(p, values);
            }

            values.add(st.getObject());
        }

        return map;
    }
}
